<template>
<div class="import-stutips">
  <el-scrollbar class="import_table" :wrap-class="isAdd ? 'vacade-scroll' : ''">
    <el-form ref="form" v-bind="getFormProps()" :label-width="isAdd ? '100px' : '142px'">
      <el-form-item label="头像：" prop="headPicture" v-if="getFormShow('headPicture')" :required="this.isSet && getFormShow('headPicture')" 
        class="form-item-avatar"
        :rules=" this.isSet && getFormShow('headPicture') ? { required: true, message: '请上传头像'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <e-img-upload v-model="form.headPicture" :is-crop="true"/>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="学员姓名：" prop="name" :rules="[
              { required: true, message: '请输入学员姓名'},
              { min: 2, message: '请输入全名'},
              Object.assign({trigger: 'blur'}, validator.rule.userName)
            ]">
        <el-col :span="isAdd ? 22 : 18">
          <el-input :maxlength="40" v-model.trim="form.name" placeholder="请输入学员姓名" @blur="handleStudentInfo('name')"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="监护人手机：" prop="parentMobile" :rules="[
          { required: true, message: '请输入手机号'},
          Object.assign({trigger: 'blur'}, validator.rule.mobile)
        ]">
        <el-row>
          <el-col :span="isAdd ? 22 : 18" class="relative">
            <el-input v-model="form.parentMobile" :maxlength="11" placeholder="请输入手机号" :disabled="isAdd?false: true" />
            <p class="small parent-phone-tips">若要修改手机号，请该监护人在"求苗"APP操作"我的"-"设置"-"账号安全"-"账号绑定"-"手机号"进行修改</p>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="校区：" prop="schoolId" v-if="isSet && type" :rules="[
        { required: true, message: '请选择校区'}, 
        Object.assign({trigger: 'blur', validator: noCheck})
      ]">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-select v-model="form.schoolId" placeholder="请选择校区" style="width:100%;">
              <el-option v-for="(item, index) in train_scholl_type_list" :key="index" :label="item.value" :value="item.key"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="班别：" prop="classesId" v-if="isSet && type" :rules="[
        { required: true, message: '请选择班别'}, 
        Object.assign({trigger: 'blur', validator: noCheck})
      ]">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-select v-model="form.classesId" placeholder="请选择班别" style="width:100%;" @change="handleClass">
              <el-option v-for="(item, index) in train_class_type_list" :key="index" :label="item.value" :value="item.key"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="次课类型：" prop="timesCourseCode" v-if="isSet && type" :rules="[
        { required: true, message: '请选择次课类型'}, 
        Object.assign({trigger: 'blur', validator: noCheck})
      ]">
        <el-row>
          <el-col :span="isAdd ? 22 : 18" style="margin-right: 5px;">
            <el-select v-model="form.timesCourseCode" placeholder="请选择次课类型" style="width:100%;">
              <el-option v-for="(item, index) in ckList" :key="index" :value="item.timesCourseCode" :label="item.timesCourseText"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="所在省市：" prop="locationOrigin" v-if="getFormShow('locationOrigin')" :required="this.isSet && getFormShow('locationOrigin')" 
        :rules="this.isSet && getFormShow('locationOrigin') ? { required: true, message: '请选择学员所在校区的省市'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <e-address-cascader v-model="form.locationOrigin" :clearable="true"  style="width: 100%" :grade="2" placeholder="请选择学员所在校区的省市"  @change ="campusChange"/>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="校区：" prop="campus" v-if="getFormShow('campus')" :required="this.isSet && getFormShow('campus')" 
        :rules="this.isSet && getFormShow('campus') ? { required: true, message: '请选择校区'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-select v-model="form.campus" :clearable="true" placeholder="请选择校区" style="width: 100%">
              <el-option v-for="(item, index) in campusData" :key="index" :value="item.id" :label="item.schoolName">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="电子邮件：" prop="email" v-if="getFormShow('email')" :required="this.isSet && getFormShow('email')" 
        :rules="this.isSet && getFormShow('email') ? { required: true, message: '请输入电子邮件'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input v-model="form.email" placeholder="请输入电子邮件" :maxlength="100"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="性别：" prop="sex" v-if="getFormShow('sex')" :required="this.isSet && getFormShow('sex')" 
        :rules="this.isSet && getFormShow('sex') ? { required: true, message: '请选择性别'} : { validator: noCheck, trigger: 'blur' }">
        <el-radio-group v-model="form.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="证件号码：" prop="idNo" v-if="getFormShow('idNo')" :required="this.isSet && getFormShow('idNo')" 
        :rules="[
          this.isSet && getFormShow('idNo') ? { required: true, message: '请输入证件号码'} : { validator: noCheck, trigger: 'blur' },
          Object.assign({trigger: 'blur', validator: validator.rule.isIp.validator.bind(this)})
        ]">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <e-identity :select-value.sync="form.idType" v-model="form.idNo" @blur="handleIp(form.idNo)" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="出生日期：" prop="birthday" v-if="getFormShow('birthday')" :required="this.isSet && getFormShow('birthday')" 
        :rules="this.isSet && getFormShow('birthday') ? { required: true, message: '请选择出生日期'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-date-picker
              :editable="true"
              v-model="form.birthday"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              :clearable="true"
              style="width: 100%">
            </el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="国籍：" prop="nationality" v-if="getFormShow('nationality')" :required="this.isSet && getFormShow('nationality')" 
        :rules="this.isSet && getFormShow('nationality') ? { required: true, message: '请选择国籍'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-select v-model="form.nationality" placeholder="请选择国籍" style="width: 100%" filterable>
              <el-option v-for="item in country_list" :key="item.id" :value="item.countryCode" :label="item.countryChineseName">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="籍贯：" prop="origin" v-if="form.nationality === '100000' && getFormShow('origin')" 
        :required="this.isSet && getFormShow('origin')" :rules="this.isSet && getFormShow('origin') ? { required: true, message: '请选择籍贯'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <e-address-cascader v-model="form.origin" :clearable="true" :grade="2" placeholder="请选择籍贯"/>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="民族：" prop="nation" v-if="getFormShow('nation')" :required="this.isSet && getFormShow('nation')" 
        :rules="this.isSet && getFormShow('nation') ? { required: true, message: '请输入民族'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="10" v-model.trim="form.nation" placeholder="请填写学员的民族"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="身高：" prop="height" v-if="getFormShow('height')" :required="this.isSet && getFormShow('height')" 
        :rules="this.isSet && getFormShow('height') ? { validator: checkNum, trigger: 'blur' } : { validator: validator.rule.limitedHeight.validator.bind(this), trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input-number v-model="form.height" placeholder="请填写学员的身高" >
              <template slot="append">CM</template>
            </el-input-number>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="体重：" prop="weight" v-if="getFormShow('weight')" :required="this.isSet && getFormShow('weight')" 
        :rules="this.isSet && getFormShow('weight') ? { validator: checkNum, trigger: 'blur' } : { validator: validator.rule.limitedWeight.validator.bind(this), trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input-number  :bit="0.01" v-model="form.weight" placeholder="请填写学员的体重"  >
              <template slot="append">KG</template>
            </el-input-number>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="运动项目：" prop="sportItem" v-if="getFormShow('sportItem')" :required="this.isSet && getFormShow('sportItem')" 
        :rules="this.isSet && getFormShow('sportItem') ? { required: true, message: '请输入运动项目'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="200" v-model.trim="form.sportItem" placeholder="请填写学员的运动项目"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="专业特点：" prop="trait" v-if="getFormShow('trait')" :required="this.isSet && getFormShow('trait')" 
        :rules="this.isSet && getFormShow('trait') ? { required: true, message: '请输入专业特点或特色'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="200" v-model.trim="form.trait" placeholder="请填写学员的专业特点或特色"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="所获奖项：" prop="awardsItem" v-if="getFormShow('awardsItem')" :required="this.isSet && getFormShow('awardsItem')" 
        :rules="this.isSet && getFormShow('awardsItem') ? { required: true, message: '请输入所获奖项'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="200" v-model.trim="form.awardsItem" placeholder="请填写学员所获得的奖项"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="监护人姓名： " prop="parentName" v-if="getFormShow('parentName')" :required="this.isSet && getFormShow('parentName')" 
        :rules="[
          this.isSet && getFormShow('parentName') ? { required: true, message: '请输入监护人姓名'} : { validator: noCheck, trigger: 'blur' },
          { min: 2, message: '请填写学员的监护人姓名'},
          Object.assign({trigger: 'blur'}, validator.rule.userName)
        ]">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="40" v-model="form.parentName" placeholder="请填写学员的监护人姓名"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="家庭住址：" prop="address" v-if="getFormShow('address')" :required="this.isSet && getFormShow('address')" 
        :rules="this.isSet && getFormShow('address') ? { required: true, message: '请输入家庭住址'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="200" v-model="form.address" placeholder="请填写学员家庭住址"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="就读学校：" prop="school" v-if="getFormShow('school')" :required="this.isSet && getFormShow('school')" 
        :rules="this.isSet && getFormShow('school') ? { required: true, message: '请输入就读学校'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="30" v-model.trim="form.school" placeholder="请填写学员就读学校"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="报名费：" prop="signupFee" v-if="isSet" required>
        <el-row>
          <el-col :span="isAdd ? 22 : 18" style="margin-right: 5px;">
            <e-input-money v-model="form.signupFee" placeholder="请填写报名费"/>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="备注：" prop="remark" :required="this.isSet && getFormShow('remark')" 
        :rules=" this.isSet && getFormShow('remark') ? { required: true, message: '请输入备注'} : { validator: noCheck, trigger: 'blur' }">
        <el-row>
          <el-col :span="isAdd ? 22 : 18">
            <el-input :maxlength="200" v-model.trim="form.remark"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-scrollbar>
  <div :class="{btnFooter: !isAdd, btnAddFooter: isAdd}">
    <el-button type="primary" @click="submit()" :loading="loading">确 定</el-button>
  </div>
</div>
</template>

<script>
import { form } from 'utils/mixins'
import validator from 'utils/validator'
import EAddressCascader from '@e-ui/AddressCascader'
import EImgUpload from '@e-ui/ImgUpload'
import { mapGetters } from 'vuex'
import api from 'api/train'
import EIdentity from '@e-ui/Identity'
import EInputMoney from '@e-ui/InputMoney'
export default {
  mixins: [form],
  props: {
    studentInfo: {
      type: Object
    },
    isAdd: {
      type: Boolean,
      default: false
    },
    formList: { // 自定义form
      type: Array,
      default: []
    },
    isSet: { // 是否自定义表单
      type: Boolean,
      default: false
    },
    type: { // 是否为次课
      type: Boolean,
      default: false
    }
  },
  components: {
    EAddressCascader,
    EIdentity,
    EInputMoney,
    EImgUpload
  },
  computed: {
    ...mapGetters({
      country_list: 'country_list',
      isLoading: 'loading',
      train_scholl_type_list: 'train_scholl_type_list',
      train_class_type_list: 'train_class_type_list',
      train_ck_course_list: 'train_ck_course_list'
    })
  },
  data () {
    return {
      checkNum: (rule, value, callback) => {
        if (value > 0 && value % 1 === 0) {
          callback()
        } else {
          callback(new Error('请输入大于0的正整数'))
        }
      },
      noCheck: (rule, value, callback) => {
        callback()
      },
      validator,
      loading: false,
      form: {
        name: '',
        sex: '',
        nationality: '',
        idType: 1,
        idNo: '',
        address: '',
        birthday: '',
        parentMobile: '',
        parentName: '',
        remark: '',
        school: '',
        height: '',
        weight: '',
        sportItem: '',
        trait: '',
        awardsItem: '',
        origin: [],
        signupFee: 0,
        nation: '',
        schoolId: '',
        courseId: '',
        classesId: '',
        email: '',
        timesCourseCode: '',
        campus: '',
        campusLabel: '',
        locationOrigin: [],
        headPicture: ''
      },
      ckList: [],
      campusData: [],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  created () {
    // v2.6.1学员报名 独立页面处理 通过 studentInfo传递 courseId
    this.form.courseId = this.studentInfo.courseId || this.$route.query.id
  },
  mounted () {
    if (this.$route.query.type === '2') {
      this.$store.dispatch('train_scholl_type_list', {courseId: this.form.courseId})
      this.$store.dispatch('train_class_type_list', {courseId: this.form.courseId})
    } else if (!this.$route.fullPath.includes('/training/curriculum/studentSign')) {
      this.$store.dispatch('country_list')
    }
  },
  watch: {
    studentInfo (value) {
      let f = this.form
      f.name = value.name
      f.parentMobile = value.parentMobile
      f.sex = value.sex
      f.idType = value.idType
      f.idNo = value.idNo
      f.birthday = value.birthday
      f.nationality = value.nationality
      f.origin = value.origin
      f.nation = value.nation
      f.height = value.height
      f.weight = value.weight
      f.address = value.address
      f.parentName = value.parentName
      f.school = value.school
      f.sportItem = value.sportItem
      f.trait = value.trait
      f.awardsItem = value.awardsItem
      f.signupFee = value.signupFee || 0
      f.remark = value.remark
      f.locationOrigin = value.locationOrigin
      f.schoolId = value.schoolId
      f.courseId = value.courseId || this.form.courseId
      f.classesId = value.classesId
      f.timesCourseCode = value.timesCourseCode
      f.email = value.email
      f.campus = value.campus || value.schoolId || value.schoolName || ''
      // f.armReach = value.armReach
      // f.standingReach = value.standingReach
      f.headPicture = value.headPicture
    },
    'form.locationOrigin' (newVl) {
      if (!this.$firstRender && newVl && newVl.length > 0) {
        api.getSchoolListByProCity({provinceId: newVl[0] || '', cityId: newVl[1]}).then((res) => {
          this.campusData = res.data
        })
        this.$firstRender = true
      } else {
        this.form.campus = ''
      }
    }
  },
  methods: {
    handleIp (value) { // 根据身份证自动输入生日日期
      if (this.form.idType) {
        this.form.birthday = new Date(`${value.substring(6, 10)}-${value.substring(10, 12)}-${value.substring(12, 14)}`).getTime()
      }
      this.handleStudentInfo('idNo')
    },
    handleCancel () {
      history.back()
    },
    handleClass (value) {
      if (value) {
        this.$store.dispatch('train_ck_course_list', {courseId: this.form.courseId, classLevelId: value}).then((res) => {
          this.ckList = this.train_ck_course_list
        })
      }
    },
    submit () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.$route.fullPath.includes('edit')) {
            let data = Object.assign({birthday: this.form.birthday ? new Date(this.form.birthday).getTime() : '', id: this.form.courseId}, this.form)
            if (!data.campus) {
              data.schoolId = ''
              data.campus = -1
            } else {
              // data.campus = data.schoolId
            }
            api.editStudent(JSON.stringify(data), {context: this, successMsg: '修改成功'}).then(res => {
              history.back()
            })
          } else {
            if (!this.$route.fullPath.includes('/training/student/add')) {
              delete this.form.campus
              delete this.form.locationOrigin
              delete this.form.email
            } else if (this.$route.query.type !== 2) {
              delete this.form.schoolId
              delete this.form.classesId
              delete this.form.courseId
            }
            let data = Object.assign({birthday: this.form.birthday ? new Date(this.form.birthday).getTime() : ''}, this.form)
            this.$emit('success', data).$emit('input', false)
          }
        }
      })
    },
    getFormShow (prop) { // 根据prop查看自定义项是否显示
      let isShow = false
      this.formList.forEach((item) => {
        if (item.fieldName === prop) {
          isShow = true
        }
      })
      return this.isSet ? isShow : true
    },
    handleStudentInfo (type) { // 查询并自动匹配学员信息
      if (this.isSet) {
        let hasName = this.form.name ? {name: this.form.name, idType: this.form.idType, idNo: this.form.idNo} : {idType: this.form.idType, idNo: this.form.idNo}
        let params = type === 'name' ? {name: this.form.name} : hasName
        api.queryStudentInfo(params).then((res) => {
          if (res.data && res.data.length === 1) {
            this.$emit('setInfo', res.data[0])
          }
        })
      }
    },
    campusChange (value) {
      if (value.length > 0) {
        api.getSchoolListByProCity({provinceId: value[0] || '', cityId: value[1]}).then((res) => {
          this.campusData = res.data
          this.form.campus = this.form.campusLabel = ''
        })
      } else {
        this.campusData = []
        this.form.campusLabel = this.form.campus = ''
      }
    }
  }
}
</script>

<style lang="scss">
.import-stutips{
  position: relative;
  .btnFooter {
    margin-left: 290px;
  }
  .vacade-scroll{
    max-height: 510px;
    overflow-y: scroll;
  }
  .el-scrollbar .el-scrollbar__bar{
    opacity: 1;
    transition: opacity 340ms ease-out
  }
  .btnAddFooter {
    position: absolute;
    left: 50%;
    margin-left:-29px;
    bottom:-65px;
    height:40px;
    z-index: 9999;
  }
  .el-form-item__content > .el-input, .el-cascader, .el-form-item__content > .el-select, .el-input-number{
    width: 100%;
  }
}
.form-item-avatar{
  label{
    margin-top: 40px;
  }
  .img-upload {
    height: 110px;
    width: 110px;
  }
}
.parent-phone-tips{
  color:#909090;
  line-height:20px;
  margin-top:10px;
}
</style>
